package com.letfox.redis.util;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ListOperationUtil<T> {

	@Resource(name = "redisTemplate")
	private RedisTemplate<String, T> redisTemplate;

	/**
	 * 缓存List
	 * @param key 缓存的键值
	 * @param list 缓存的List数据
	 * @return 缓存的对象
	 */
	public ListOperations<String, T> setCacheList(String key, List<T> list) {

		ListOperations<String, T> operations = redisTemplate.opsForList();
		if (list != null) {
			int size = list.size();
			for (int i = 0; i < size; i++) {
				operations.rightPush(key, list.get(i));
			}
		}
		return operations;
	}

	/**
	 * 获取缓存List对象
	 * @param key 缓存的键值
	 * @return 缓存键值对应的数据
	 */
	public List<T> getCacheList(String key) {
		List<T> list = new ArrayList<T>();
		ListOperations<String, T> operations = redisTemplate.opsForList();
		Long size = operations.size(key);
		for (int i = 0; i < size; i++) {
			list.add(operations.leftPop(key));
		}
		return list;
	}
}
